package com.zlt.controller.recruiter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zlt.controller.BaseController;
import com.zlt.dto.OfferDto;
import com.zlt.service.OfferService;
import com.zlt.service.impl.OfferServiceImpl;
import com.zlt.util.ClassUtil;
import com.zlt.util.EmailUtil;
import com.zlt.util.QnyUtil;
import com.zlt.util.StringUtil;
import com.zlt.vo.OfferVo;
import com.zlt.vo.Pager;
import com.zlt.vo.Result;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

/**
 * offer状态 0已发送 1默认保存  2已接收 3 已拒绝 4删除
 */
@WebServlet("/recruiter/offer/*")
@MultipartConfig
public class OfferController extends BaseController {

    //offer服务层对象
    private OfferService offerService=new OfferServiceImpl();

    /**
     * 执行默认方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void defaultMethod(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    /**
     * 添加offer
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected Result addOffer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String email = req.getParameter("email");
        String phone = req.getParameter("username");
        String validTime = req.getParameter("validTime");
        String content = req.getParameter("content");
        Part offerFile =null;
        //文件上传失败，未写完
//          offerFile=req.getPart("offerFile");

        try {
            boolean isSuccess=offerService.addOffer(email,phone,validTime,content,offerFile);
            return isSuccess ? Result.ok("添加成功"):Result.error("添加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败");
        }
    }


    /**
     * 发送offer
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result sendOffer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OfferDto offerDto = ClassUtil.resolveRequest(OfferDto.class, req);
        System.out.println(offerDto.toString());
        boolean isSuccess=false;
        try {
            isSuccess=offerService.sendOffer(offerDto);
            return isSuccess ? Result.ok("发送成功"):Result.error("发送失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }


    /**
     * 查询所有的offer
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result allOffer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = req.getParameter("page");
        if (!StringUtil.isNotNull(page)){
            page = "1";
        }
        String limit = req.getParameter("limit");
        if (!StringUtil.isNotNull(limit)){
            limit = "5";
        }
        Pager<OfferVo> pager=new Pager<>();
        pager.setPage(Integer.parseInt(page));
        pager.setLimit(Long.parseLong(limit));

        try {
             pager=offerService.selectAllOffer(pager);
            System.out.println(pager.toString());
            return Result.ok("offer查询成功",pager);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("offer查询错误");
        }

    }

    /**
     * 删除offer
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result deleteOffer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String data = req.getParameter("data");
        JSONArray objects = JSON.parseArray(data);
        List<OfferVo> offerVoList=new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            OfferVo offerVo=new OfferVo();
            offerVoList.add(offerVo);
            try {
                BeanUtils.copyProperties(offerVo,objects.get(i));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        try {
            boolean isSuccess=offerService.deleteOffer(offerVoList);
            return isSuccess ? Result.ok("删除成功"):Result.error("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    /**
     * 更新offer内容,只能更新处于保存状态的offer
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result updateOffer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        OfferDto offerDto=ClassUtil.resolveRequest(OfferDto.class,req);

        try {
            boolean isSuccess=offerService.updateOffer(offerDto);
            return isSuccess ? Result.ok("修改成功"):Result.error("修改失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    /**
     * 发送离线offer
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result sendOfflineOffer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String email = req.getParameter("email");
        String subject = req.getParameter("subject");
        String content = req.getParameter("content");
        Part offlineOffer = req.getPart("offlineOffer");

        OfferDto offerDto=ClassUtil.resolveRequest(OfferDto.class,req);
        if(offerDto==null){
            return Result.error("发送失败");
        }
        System.out.println("offDto==="+offerDto.toString());


        String url="";
        if(offlineOffer!=null) {
            if (offlineOffer.getSize() > 0) {
                String submittedFileName = offlineOffer.getSubmittedFileName();
                String fileName = "offer" + UUID.randomUUID() + submittedFileName.substring(submittedFileName.lastIndexOf("."));
                String path="D:\\JavaPractice\\files";
                File file=new File(path);
                if(!file.isDirectory()){
                    file.mkdirs();
                }
                String savePath = path + File.separator + fileName;
                String upload = QnyUtil.upload(offlineOffer.getInputStream(), fileName);
                System.out.println("犀牛云："+upload);
                try {
                    offlineOffer.write(savePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //访问路径
                url = "http://localhost:8080//files" + File.separator + fileName;
                boolean isSuccess = EmailUtil.sendEmailAnnex(email, subject, content, savePath);
                if (isSuccess) {
                    isSuccess = offerService.addOfflineOffer(offerDto, upload);
                    return Result.ok("发送成功" + (isSuccess ? "保存成功" : "保存失败"));
                }
            }
        }
        return Result.error("发送失败");
    }

}
